<?php
include "include/db.php";

    if (isset($_POST['submit'])) //  Do  THE FOLLOWING WHEN BUTTON IS PRESSED
        {
            if ($_FILES["file"]["error"] > 0)
                {
                        echo "Error: " . $_FILES["file"]["error"] . 
			"You have not selected a file or some other error <br />";
                }
            else
                {       //              Errorless  start 
                        $file_name=$_FILES["file"]["name"];
                        $file_type=$_FILES["file"]["type"];
                        
                 if($file_type!='application/vnd.ms-excel')
                    {
                                echo "Please the input file should be a .csv file";
                    }
                 else
                    {       
                            // only executed if file is .csv
                            //echo "its correct";
                                
                            // Creating a temporary copy on the server 
                    
                            $location="data/"; // write the location on 
                            
                            // server where a copy should be created
                            $file_move = move_uploaded_file($_FILES["file"]["tmp_name"],
                            $location . $_FILES["file"]["name"]);
                            
                            // open the csv file
                            $data = file('data/'.$file_name);

                            // create an insert statement for each row in the csv file
                            foreach ($data as $row)
                                {
                                    $cols = explode(",", $row); // put each piece of data seperated by a comma, into an array called $cols
                                    $sql = "INSERT INTO address (name,line1, line2, city, postcode) VALUES ('$cols[0]', '$cols[1]', '$cols[2]', '$cols[3]', '$cols[4]')";
                                    mysql_query($sql)or die(mysql_error());
                                    
                                 }
                                 if($sql)
                                    {?>
                                    <script>
                                        alert("Your Data is stored.");
                                        window.location="list.php";
                                    </script>
                                    <?php 
                                    
                                    }
                          } 
                   }
        }
?>